package com.supermarket.util;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 审计日志工具类
 * 用于记录系统操作的审计日志
 */
public class AuditLogger {
    private static final String LOG_FILE = "logs/audit.log";
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    /**
     * 记录操作审计日志
     * 
     * @param userId 操作用户ID
     * @param operation 操作类型
     * @param details 操作详情
     * @param result 操作结果
     */
    public static void logOperation(Integer userId, String operation, String details, String result) {
        try {
            // 确保日志目录存在
            java.io.File logDir = new java.io.File("logs");
            if (!logDir.exists()) {
                logDir.mkdirs();
            }
            
            try (PrintWriter writer = new PrintWriter(new FileWriter(LOG_FILE, true))) {
                String timestamp = DATE_FORMAT.format(new Date());
                String logEntry = String.format("[%s] 用户ID:%s | 操作:%s | 详情:%s | 结果:%s%n", 
                    timestamp, userId, operation, details, result);
                writer.print(logEntry);
                writer.flush();
            }
        } catch (IOException e) {
            System.err.println("写入审计日志失败: " + e.getMessage());
        }
    }
    
    /**
     * 记录临期商品申报操作
     */
    public static void logExpiringProductDeclaration(Integer userId, Integer productId, String action, boolean success) {
        String operation = "临期商品申报";
        String details = String.format("商品ID:%d, 处理方式:%s", productId, action);
        String result = success ? "成功" : "失败";
        logOperation(userId, operation, details, result);
    }
    
    /**
     * 记录临期商品审批操作
     */
    public static void logExpiringProductApproval(Integer userId, Integer reportId, String status, String remarks) {
        String operation = "临期商品审批";
        String details = String.format("申报ID:%d, 审批状态:%s, 备注:%s", reportId, status, remarks);
        String result = "完成";
        logOperation(userId, operation, details, result);
    }
    
    /**
     * 记录数据库操作异常
     */
    public static void logDatabaseError(String operation, String error) {
        String details = String.format("数据库操作:%s, 错误信息:%s", operation, error);
        logOperation(null, "数据库异常", details, "失败");
    }
    
    /**
     * 记录数据验证失败
     */
    public static void logValidationError(Integer userId, String operation, String validationError) {
        String details = String.format("操作:%s, 验证错误:%s", operation, validationError);
        logOperation(userId, "数据验证失败", details, "失败");
    }
}